package com.example.interviewdemo.reentrantLock;

/**
 * @program my-project-model
 * @description:
 * @author: lee
 * @create: 2023/01/04 09:43
 */
public class ReentrantLock {

    private boolean isLocked = false;
    /**
     * 用于记录是不是重入的线程
     */
    private Thread lockedOwner = null;
    /**
     * 记录上锁的次数，上一次锁 +1
     * 解锁一次 -1
     */
    private int lockedCount = 0;

    /**
     * 判断是否已经被锁，如果锁住了则当前请求的线程进行等待
     * <p>
     * 否则进行加锁
     */
    public synchronized void lock() throws InterruptedException {
        System.out.println("进入lock加锁" + Thread.currentThread().getName());
        Thread thread = Thread.currentThread();
        System.out.println("当前锁状态isLocked=" + isLocked);
        System.out.println("当前锁的count数量=" + lockedCount);
        //判断当前线程是否是同一个线程获取锁,引用地址的比较
        while (isLocked && lockedOwner != thread) {
            System.out.println("进入wait等待" + Thread.currentThread().getName());
            wait();
        }

        isLocked = true;
        lockedOwner = thread;
        lockedCount++;
    }

    /**
     * 解锁操作
     */
    public synchronized void unLock() {
        System.out.println("进入unlock解锁" + Thread.currentThread().getName());
        Thread thread = Thread.currentThread();
        //只能让加锁的线程解锁
        if (thread == this.lockedOwner) {
            lockedCount--;
            if (lockedCount == 0) {
                isLocked = false;
                lockedOwner = null;
                //唤醒对象锁池里的一个线程
                notify();
            }
        }


    }

}
